package com.zygk.xmpp.adapter;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.flyco.roundview.RoundTextView;
import com.mabeijianxi.smallvideorecord2.MediaRecorderActivity;
import com.zygk.library.util.DateUtil;
import com.zygk.library.util.GlideImageLoader;
import com.zygk.library.util.ImageManager;
import com.zygk.library.util.ImageUtil;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.util.Util;
import com.zygk.xmpp.R;
import com.zygk.xmpp.activity.ChatActivity;
import com.zygk.xmpp.activity.VideoPlayerActivity;
import com.zygk.xmpp.dao.MsgDbHelper;
import com.zygk.xmpp.model.M_ChatItem;
import com.zygk.xmpp.util.Constants;
import com.zygk.xmpp.view.expression.ExpressionUtil;
import com.zygk.xmpp.view.gifView.GifView;
import com.zygk.xmpp.xmpp.MessageConstants;
import com.zygk.xmpp.xmpp.XmppConnection;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.jivesoftware.smackx.packet.VCard;
import org.json.JSONObject;

public class OldChatAdapter extends ArrayAdapter<M_ChatItem> {
  private Context cxt;
  private static int[] resTo = {
      R.mipmap.xmpp_icon_voiceto0, R.mipmap.xmpp_icon_voiceto1, R.mipmap.xmpp_icon_voiceto2,
      R.mipmap.xmpp_icon_voiceto3
  };
  private static int[] resFrom = {
      R.mipmap.xmpp_icon_voicefrom0, R.mipmap.xmpp_icon_voicefrom1, R.mipmap.xmpp_icon_voicefrom2,
      R.mipmap.xmpp_icon_voicefrom3
  };
  private String username = null;
  ChatActivity activity;
  protected ImageManager mImageManager;
  private HashMap<String, String> map = new HashMap();

  public interface MsgType {
    int MSG_OUT = 0;
    int MSG_IN = 1;
  }

  public OldChatAdapter(ChatActivity activity, Context context, String username) {
    super(context, 0);
    this.activity = activity;
    this.cxt = context;
    this.username = username;

    mImageManager = new ImageManager(context);
  }

  @Override public int getItemViewType(int position) {
    M_ChatItem nowMsg = getItem(position);
    if (nowMsg.getInOrOut() == 1) {
      return MsgType.MSG_OUT;
    } else {
      return MsgType.MSG_IN;
    }
  }

  @Override public int getViewTypeCount() {
    return 2;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
    final M_ChatItem item = getItem(position);
    final ViewHolder viewHolder;
    int msgType = getItemViewType(position);

    if (convertView == null) {
      if (msgType == MsgType.MSG_OUT) {
        convertView = LayoutInflater.from(cxt).inflate(R.layout.xmpp_row_chat_mine, null, false);
      } else {
        convertView = LayoutInflater.from(cxt).inflate(R.layout.xmpp_row_chat, null, false);
      }

      viewHolder = new ViewHolder();
      viewHolder.timeView = convertView.findViewById(R.id.timeView);
      viewHolder.msgView = convertView.findViewById(R.id.msgView);
      viewHolder.head = convertView.findViewById(R.id.headImg);
      viewHolder.img = convertView.findViewById(R.id.imgView);
      viewHolder.flMap = convertView.findViewById(R.id.fl_map);
      viewHolder.map = convertView.findViewById(R.id.iv_map);
      viewHolder.address = convertView.findViewById(R.id.tv_map);
      viewHolder.gifImg = convertView.findViewById(R.id.gifImgView);
      viewHolder.voice = convertView.findViewById(R.id.voiceView);
      viewHolder.soundDuration = convertView.findViewById(R.id.soundView);
      viewHolder.flMovieView = convertView.findViewById(R.id.fl_movieView);
      viewHolder.movie = convertView.findViewById(R.id.iv_movieView);
      viewHolder.movieDuration = convertView.findViewById(R.id.tv_duration);
      viewHolder.gif = convertView.findViewById(R.id.gifView);
      viewHolder.nameView = convertView.findViewById(R.id.nameView);
      viewHolder.textimg = convertView.findViewById(R.id.textimgView);
      convertView.setTag(viewHolder);
    } else {
      viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.msgView.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        //Intent intent = new Intent(cxt, VideoActivity.class);
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Bundle bundle = new Bundle();
        //bundle.putString("videoPath", item.getMsg());
        //bundle.putBoolean("useCache", false);
        //intent.putExtras(bundle);
        //cxt.startActivity(intent);
      }
    });

    //head
    if (item.getInOrOut() == 0) {   //接收
      if (item.getChatType() == M_ChatItem.CHAT) {
        Bitmap bmp = MessageConstants.findAllHeadById(item.getUsername());
        if (bmp != null) {
          viewHolder.head.setImageBitmap(bmp);
        }
      }
      if (map.get(item.getUsername()) == null) {
        VCard vcard = XmppConnection.getInstance().getUservcard(item.getUsername());
        map.put(item.getUsername(), vcard.getField("Name"));
        item.setUsername(vcard.getField("Name"));
      } else {
        item.setUsername(map.get(item.getUsername()));
      }
    } else {
      if (item.getChatType() == M_ChatItem.CHAT) {
        Bitmap bmp = MessageConstants.findAllHeadById(Constants.XMPP_USERNAME);
        if (bmp != null) {
          viewHolder.head.setImageBitmap(bmp);
        }
      }

      item.setUsername(Constants.XMPP_NICKNAME);
    }

    //同一分钟内则不显示相同时间了
    M_ChatItem lastMsg = null;
    if (position != 0) lastMsg = (M_ChatItem) getItem(position - 1);
    if (lastMsg != null && lastMsg.getSendDate()
        .substring(0, 12)
        .equals(item.getSendDate().substring(0, 12))) {
      viewHolder.timeView.setVisibility(View.GONE);
    } else if (item.getIsbit() == 0) {
      viewHolder.timeView.setVisibility(View.GONE);
    } else {
      viewHolder.timeView.setVisibility(View.VISIBLE);
      viewHolder.timeView.setText(DateUtil.getRecentTimeMM_dd(item.getSendDate()));
    }

    String json = item.getMsg();
    JSONObject obj = null;
    try {
      obj = new JSONObject(json);
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      if ("0".equals(item.getBodyType())) {
        viewHolder.msgView.setVisibility(View.VISIBLE);
        viewHolder.img.setVisibility(View.GONE);
        viewHolder.soundDuration.setVisibility(View.GONE);
        viewHolder.voice.setVisibility(View.GONE);
        viewHolder.flMovieView.setVisibility(View.GONE);
        viewHolder.flMap.setVisibility(View.GONE);
        viewHolder.map.setVisibility(View.GONE);

        String msg = obj.getString("msg");
        viewHolder.msgView.setText(ExpressionUtil.getText(cxt, StringUtils.Unicode2GBK(msg)));
        //if (msg != null && msg.contains("[/g0")) { // isGif
        //  playGif(viewHolder.gif, viewHolder.msgView, viewHolder.gifImg, msg, position);
        //} else { // 适配中文表情
        //}
      } else if ("2".equals(item.getBodyType())) {     //图片
        viewHolder.msgView.setVisibility(View.GONE);
        viewHolder.img.setVisibility(View.VISIBLE);
        viewHolder.soundDuration.setVisibility(View.GONE);
        viewHolder.voice.setVisibility(View.GONE);
        viewHolder.flMovieView.setVisibility(View.GONE);
        viewHolder.flMap.setVisibility(View.GONE);
        viewHolder.map.setVisibility(View.GONE);

        String path = obj.getString("msg");
        showImg(viewHolder.img, path);
      } else if ("3".equals(item.getBodyType())) {    //语音
        viewHolder.msgView.setVisibility(View.GONE);
        viewHolder.img.setVisibility(View.GONE);
        viewHolder.soundDuration.setVisibility(View.VISIBLE);
        viewHolder.voice.setVisibility(View.VISIBLE);
        viewHolder.flMovieView.setVisibility(View.GONE);
        viewHolder.flMap.setVisibility(View.GONE);
        viewHolder.map.setVisibility(View.GONE);

        String path = item.getMsg();
        playSound(path, viewHolder.soundDuration, viewHolder.voice, item.getInOrOut() == 1);
      } else if ("5".equals(item.getBodyType())) {    //小视频
        viewHolder.msgView.setVisibility(View.GONE);
        viewHolder.img.setVisibility(View.GONE);
        viewHolder.soundDuration.setVisibility(View.GONE);
        viewHolder.voice.setVisibility(View.GONE);
        viewHolder.flMovieView.setVisibility(View.VISIBLE);
        viewHolder.flMap.setVisibility(View.GONE);
        viewHolder.map.setVisibility(View.GONE);

        String path = obj.getString("msg");
        playMovie(path, viewHolder.movieDuration, viewHolder.movie, item.getInOrOut() == 1);
      } else if ("6".equals(item.getBodyType())) {    //定位
        viewHolder.msgView.setVisibility(View.GONE);
        viewHolder.img.setVisibility(View.GONE);
        viewHolder.soundDuration.setVisibility(View.GONE);
        viewHolder.voice.setVisibility(View.GONE);
        viewHolder.flMovieView.setVisibility(View.GONE);
        viewHolder.flMap.setVisibility(View.VISIBLE);
        viewHolder.map.setVisibility(View.VISIBLE);

        viewHolder.address.setText(obj.getString("name"));
        showPosition(viewHolder.map, obj);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (item.getChatType() == M_ChatItem.GROUP_CHAT) {
      viewHolder.nameView.setVisibility(View.VISIBLE);
      viewHolder.nameView.setText(item.getUsername());
    } else {
      viewHolder.nameView.setVisibility(View.GONE);
    }

    //内容复制
    viewHolder.msgView.setOnLongClickListener(new OnLongClickListener() {
      @SuppressLint("NewApi") @Override public boolean onLongClick(View v) {
        TextView msgView = (TextView) v;
        ClipboardManager cm = (ClipboardManager) cxt.getSystemService(Context.CLIPBOARD_SERVICE);
        //将文本数据复制到剪贴板
        cm.setText(msgView.getText());
        Vibrator vib = (Vibrator) cxt.getSystemService(Context.VIBRATOR_SERVICE);  //震动提醒
        vib.vibrate(100);
        ToastUtil.showMessage(cxt, "复制成功");
        return false;
      }
    });
    return convertView;
  }

  private void showImg(ImageView img, final String path) {
    GlideImageLoader glideImageLoader = new GlideImageLoader();
    glideImageLoader.displayImage(activity, path, img, 200, 200);
    //img.setImageBitmap(ImageUtil.createImageThumbnail(path, 200 * 200));
    img.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        //Intent intent = new Intent();
        //intent.putExtra("picPath", path);
        //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent.setClass(cxt, ShowPicActivitiy.class);
        //cxt.startActivity(intent);
      }
    });

    img.setOnLongClickListener(new OnLongClickListener() {
      @SuppressLint("NewApi") @Override public boolean onLongClick(View v) {
        //				FileUtil.changeFile(path, CircleConstants.IMG_PATH+"/"+FileUtil.getFileName(path));
        ToastUtil.showMessage(cxt, "图片已保存至本地" + path);
        cxt.sendBroadcast(
            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        return false;
      }
    });
  }

  private void showPosition(ImageView img, final JSONObject obj) {
    try {
      final String path = obj.getString("imageUrl");
      mImageManager.loadRoundImage(path, img, 13);

      //			img.setImageBitmap(ImageUtil.createImageThumbnail(path,200*200));
      //			Bitmap bm = getRoundedCornerBitmap(compressImage(Utils.createVideoThumbnail((String)map.get("msgUrl"))));
      //			BitmapDrawable drawable = new BitmapDrawable(bm);
      //			img.setBackgroundDrawable(drawable);

      //ViewGroup.LayoutParams para;
      //para = img.getLayoutParams();
      //para.width = 600 * ContextUtil.width / 1080;
      //para.height = para.width / 2;
      //img.setLayoutParams(para);
      //
      //img.setOnLongClickListener(new OnLongClickListener() {
      //  @SuppressLint("NewApi") @Override public boolean onLongClick(View v) {
      //    //					FileUtil.changeFile(path, CircleConstants.IMG_PATH+"/"+FileUtil.getFileName(path));
      //    Tool.initToast(cxt, "图片已保存至本地" + path);
      //    ContextUtil.getInstance()
      //        .sendBroadcast(
      //            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
      //    return false;
      //  }
      //});
      //
      //img.setOnClickListener(new OnClickListener() {
      //  @SuppressLint("NewApi") @Override public void onClick(View v) {
      //    try {
      //      Intent intent = new Intent(cxt, ShowMapActivity.class);
      //      intent.putExtra("lat", obj.getString("lat"));
      //      intent.putExtra("lon", obj.getString("lon"));
      //      intent.putExtra("name", obj.getString("name"));
      //      intent.putExtra("address", obj.getString("address"));
      //      intent.putExtra("imageUrl", path);
      //      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      //      cxt.startActivity(intent);
      //    } catch (Exception e) {
      //      e.printStackTrace();
      //    }
      //  }
      //});
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * play gif
   */
  private void playGif(GifView gif, TextView msgView, ImageView img, String msg, int position) {
    msgView.setVisibility(View.GONE);
    try {
      Field field = R.drawable.class.getDeclaredField(msg.substring(2, msg.indexOf("]")));
      int resId = Integer.parseInt(field.get(null).toString());
      if (getCount() - 1 - position < 3) {   //只显示三个动态
        gif.setVisibility(View.VISIBLE);
        gif.setGifImageType(GifView.GifImageType.COVER);
        gif.setGifImage(resId);
      } else {
        img.setVisibility(View.VISIBLE);
        img.setBackgroundResource(resId);
      }
    } catch (NoSuchFieldException e) {
      msgView.setVisibility(View.VISIBLE);
      msgView.setText(ExpressionUtil.getText(cxt, StringUtils.Unicode2GBK(msg)));
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * play voice
   *
   * @param file
   * @param soundDuration
   * @param voice
   * @param isOut
   */
  public MediaPlayer mping = new MediaPlayer();

  private void playSound(String file, TextView soundDuration, final ImageView voice,
      final boolean isOut) {
    final MediaPlayer mp = new MediaPlayer();
    try {
      mp.setDataSource(file);
      mp.prepare();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    soundDuration.setText("" + mp.getDuration() / 1000 + "\"");
    voice.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        if (mp.isPlaying()) {
          mp.stop();
        } else {
          mp.start();
          mping = mp;
          new CountDownTimer(mp.getDuration(), 500) {
            int i = 0;

            @Override public void onTick(long millisUntilFinished) {
              if (i <= mp.getDuration() / 1000) {
                if (isOut) {
                  voice.setImageResource(resTo[i]);
                } else {
                  voice.setImageResource(resFrom[i]);
                }
                i++;
                if (i > 3) i = 0;
              }
            }

            @Override public void onFinish() {
              if (isOut) {
                voice.setImageResource(resTo[0]);
              } else {
                voice.setImageResource(resFrom[0]);
              }
            }
          }.start();
        }
      }
    });
  }

  private void playMovie(final String path, final TextView movieDuration, final ImageView img,
      final boolean isOut) {
    ViewGroup.LayoutParams para;
    para = img.getLayoutParams();

    //Bitmap bm = Utils.createVideoThumbnail(path);
    //Map map = ImageUtil.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
    //int width = bm.getWidth();
    //int height = bm.getHeight();

    DisplayMetrics metric = new DisplayMetrics();
    ((WindowManager) cxt.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
        .getRealMetrics(metric);
    para.width = 240 * metric.widthPixels / 1080;
    para.height = para.width * metric.heightPixels / metric.widthPixels;
    img.setLayoutParams(para);
    img.setBackgroundColor(Color.WHITE);

    if (MessageConstants.movieMap.containsKey(
        path)) {    // 网络路径（即消息msg）：http://192.168.10.201:8000/files/video/201804092100355648054_qz_camera_1523278845058.mp4
      Map map = MessageConstants.movieMap.get(path);
      BitmapDrawable drawable = new BitmapDrawable((Bitmap) map.get("bitmap"));
      img.setBackgroundDrawable(drawable);
      movieDuration.setText("0:0" + map.get("duration"));
    } else if (MsgDbHelper.getInstance(activity).getonevideoMsg(path) != null
        && MsgDbHelper.getInstance(activity).getonevideoMsg(path).size() > 0) {
      new Thread(new Runnable() {

        @Override public void run() {
          try {
            handler.sendEmptyMessage(0);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

        private Handler handler = new Handler() {
          @Override public void handleMessage(Message msg) {
            if (msg.what == 0) {
              Map map = MsgDbHelper.getInstance(activity).getonevideoMsg(path);
              Bitmap bm = getRoundedCornerBitmap(
                  compressImage(Util.createVideoThumbnail((String) map.get("msgUrl"))));
              map.put("bitmap", bm);
              MessageConstants.movieMap.put(path, map);
              BitmapDrawable drawable = new BitmapDrawable(bm);
              img.setBackgroundDrawable(drawable);
              movieDuration.setText("0:0" + map.get("duration"));
            }
          }
        };

        public Bitmap compressImage(Bitmap image) {
          // Scale down the bitmap if it's too large.
          int width = image.getWidth();
          int height = image.getHeight();
          int max = Math.max(width, height);
          if (max > 512) {
            float scale = 512f / max;
            int w = Math.round(scale * width);
            int h = Math.round(scale * height);
            image = Bitmap.createScaledBitmap(image, w, h, true);
          }//压缩图片 结束处

          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
          int options = 90;

          while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options,
                baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
          }
          ByteArrayInputStream isBm =
              new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
          Bitmap bitmap =
              BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
          return bitmap;
        }

        public Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
          Bitmap output =
              Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
          Canvas canvas = new Canvas(output);
          final int color = 0xff424242;
          final Paint paint = new Paint();
          final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
          final RectF rectF = new RectF(rect);
          final float roundPx = 13;
          paint.setAntiAlias(true);
          canvas.drawARGB(0, 0, 0, 0);
          paint.setColor(color);
          canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
          paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
          canvas.drawBitmap(bitmap, rect, rect, paint);
          return output;
        }
      }).start();
    } else {
      new Thread(new Runnable() {

        @Override public void run() {
          try {
            handler.sendEmptyMessage(0);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

        private Handler handler = new Handler() {
          @Override public void handleMessage(Message msg) {
            if (msg.what == 0) {
              Map map = Util.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
              MessageConstants.movieMap.put(path, map);
              BitmapDrawable drawable = new BitmapDrawable((Bitmap) map.get("bitmap"));
              img.setBackgroundDrawable(drawable);
              movieDuration.setText("0:0" + map.get("duration"));
            }
          }
        };
      }).start();
    }

    img.setOnClickListener(new OnClickListener() {
      @SuppressLint("NewApi") @Override public void onClick(View v) {
        if (path != null && !path.equalsIgnoreCase("")) {
          //Intent intent = new Intent(cxt, VideoPlayerActivity.class);
          //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          //Bundle bundle = new Bundle();
          //bundle.putString(MediaRecorderActivity.VIDEO_URI, path);
          //intent.putExtras(bundle);
          //cxt.startActivity(intent);
        }
      }
    });
  }

  class ViewHolder {
    TextView timeView, msgView, soundDuration, nameView, movieDuration;
    RoundTextView address;
    ImageView head, img, map, gifImg, voice, movie, textimg;
    GifView gif;
    FrameLayout flMap, flMovieView;
  }
}